<template>
    <div class="exam-results">
      <y-header title="考试成绩" left-arrow @click-left="onBack" />
      
      <div class="exam-info">
        <h3>{{ exam.title }}</h3>
        <div class="exam-details">
          <p class="description">{{ exam.description }}</p>
          <div class="exam-time">考试时间：{{ formatDate(exam.startTime) }} ~ {{ formatDate(exam.endTime) }}</div>
          <div class="exam-status">
            <van-tag :type="getStatusTagType(exam.status)">
              {{ getStatusText(exam.status) }}
            </van-tag>
          </div>
        </div>
      </div>
      
      <div class="results-summary">
        <div class="summary-card">
          <div class="summary-item">
            <div class="label">参与人数</div>
            <div class="value">{{ exam.participantCount }}/{{ exam.totalCount }}</div>
          </div>
          <div class="summary-item">
            <div class="label">平均分</div>
            <div class="value">{{ avgScore }}</div>
          </div>
          <div class="summary-item">
            <div class="label">最高分</div>
            <div class="value">{{ highestScore }}</div>
          </div>
          <div class="summary-item">
            <div class="label">及格率</div>
            <div class="value">{{ passRate }}%</div>
          </div>
        </div>
        
        <div class="score-distribution">
          <h4>分数分布</h4>
          <div class="chart-container">
            <!-- 简化版分数分布图表，实际项目可以使用echarts等 -->
            <div class="bar-chart">
              <div 
                v-for="(item, index) in scoreDistribution" 
                :key="index" 
                class="bar-item"
              >
                <div class="bar" :style="{ height: `${item.percentage}%` }"></div>
                <div class="bar-label">{{ item.range }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="toolbar">
        <van-search v-model="searchValue" placeholder="搜索学生姓名" />
        <van-dropdown-menu>
          <van-dropdown-item v-model="sortBy" :options="sortOptions" />
        </van-dropdown-menu>
      </div>
      
      <div class="results-list">
        <van-empty v-if="filteredResults.length === 0" description="暂无考试成绩" />
        
        <van-cell-group inset v-else>
          <van-cell 
            v-for="result in filteredResults" 
            :key="result.id"
            :title="result.student.name"
          >
            <template #label>
              <div class="student-info">
                <span class="student-id">学号: {{ result.student.studentId }}</span>
                <span class="submission-time">提交时间: {{ formatDate(result.submitTime) }}</span>
              </div>
            </template>
            <template #right-icon>
              <div class="score" :class="getScoreClass(result.score, exam.totalScore)">
                {{ result.score }}/{{ exam.totalScore }}
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <div class="action-buttons">
        <van-button type="primary" block @click="exportResults">导出成绩</van-button>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showSuccessToast } from 'vant';
  import YHeader from '@/components/YHeader.vue';
  
  interface Student {
    id: string;
    name: string;
    studentId: string;
    avatar?: string;
  }
  
  interface ExamResult {
    id: string;
    student: Student;
    score: number;
    submitTime: string;
    duration: number; // 分钟
    answers: any[]; // 学生答案
  }
  
  interface Exam {
    id: string;
    title: string;
    description: string;
    startTime: string;
    endTime: string;
    totalScore: number;
    status: 'not_started' | 'in_progress' | 'finished';
    participantCount: number;
    totalCount: number;
  }
  
  const router = useRouter();
  const route = useRoute();
  const courseId = computed(() => route.query.courseId as string);
  const examId = computed(() => route.query.examId as string);
  
  // 模拟数据 - 实际应该从API获取
  const exam = ref<Exam>({
    id: '1',
    title: '期中考试：Vue基础',
    description: 'Vue3组件、生命周期和响应式原理',
    startTime: '2023-11-10T09:00:00',
    endTime: '2023-11-10T11:00:00',
    totalScore: 100,
    status: 'finished',
    participantCount: 40,
    totalCount: 42
  });
  
  const results = ref<ExamResult[]>([
    {
      id: '1',
      student: {
        id: '1',
        name: '张三',
        studentId: '2021001'
      },
      score: 92,
      submitTime: '2023-11-10T10:30:00',
      duration: 90,
      answers: []
    },
    {
      id: '2',
      student: {
        id: '2',
        name: '李四',
        studentId: '2021002'
      },
      score: 85,
      submitTime: '2023-11-10T10:45:00',
      duration: 105,
      answers: []
    },
    {
      id: '3',
      student: {
        id: '3',
        name: '王五',
        studentId: '2021003'
      },
      score: 78,
      submitTime: '2023-11-10T10:55:00',
      duration: 115,
      answers: []
    },
    {
      id: '4',
      student: {
        id: '4',
        name: '赵六',
        studentId: '2021004'
      },
      score: 65,
      submitTime: '2023-11-10T11:00:00',
      duration: 120,
      answers: []
    }
  ]);
  
  const searchValue = ref('');
  const sortBy = ref('score_desc');
  const sortOptions = [
    { text: '分数从高到低', value: 'score_desc' },
    { text: '分数从低到高', value: 'score_asc' },
    { text: '提交时间从早到晚', value: 'time_asc' },
    { text: '提交时间从晚到早', value: 'time_desc' }
  ];
  
  // 统计数据
  const avgScore = computed(() => {
    if (results.value.length === 0) return 0;
    const sum = results.value.reduce((acc, result) => acc + result.score, 0);
    return Math.round((sum / results.value.length) * 10) / 10; // 保留一位小数
  });
  
  const highestScore = computed(() => {
    if (results.value.length === 0) return 0;
    return Math.max(...results.value.map(result => result.score));
  });
  
  const passRate = computed(() => {
    if (results.value.length === 0) return 0;
    const passCount = results.value.filter(result => result.score >= exam.value.totalScore * 0.6).length;
    return Math.round((passCount / results.value.length) * 100);
  });
  
  // 分数分布
  const scoreDistribution = computed(() => {
    const totalScore = exam.value.totalScore;
    const ranges = [
      { range: '0-60%', min: 0, max: totalScore * 0.6, count: 0 },
      { range: '60-70%', min: totalScore * 0.6, max: totalScore * 0.7, count: 0 },
      { range: '70-80%', min: totalScore * 0.7, max: totalScore * 0.8, count: 0 },
      { range: '80-90%', min: totalScore * 0.8, max: totalScore * 0.9, count: 0 },
      { range: '90-100%', min: totalScore * 0.9, max: totalScore, count: 0 }
    ];
    
    results.value.forEach(result => {
      for (const range of ranges) {
        if (result.score >= range.min && result.score < range.max) {
          range.count++;
          break;
        } else if (range.range === '90-100%' && result.score === totalScore) {
          range.count++;
          break;
        }
      }
    });
    
    const maxCount = Math.max(...ranges.map(r => r.count));
    
    return ranges.map(range => ({
      ...range,
      percentage: maxCount > 0 ? (range.count / maxCount) * 100 : 0
    }));
  });
  
  const filteredResults = computed(() => {
    let filtered = [...results.value];
    
    // 搜索过滤
    if (searchValue.value) {
      const keyword = searchValue.value.toLowerCase();
      filtered = filtered.filter(
        result => result.student.name.toLowerCase().includes(keyword) ||
                 result.student.studentId.toLowerCase().includes(keyword)
      );
    }
    
    // 排序
    switch (sortBy.value) {
      case 'score_desc':
        filtered.sort((a, b) => b.score - a.score);
        break;
      case 'score_asc':
        filtered.sort((a, b) => a.score - b.score);
        break;
      case 'time_asc':
        filtered.sort((a, b) => new Date(a.submitTime).getTime() - new Date(b.submitTime).getTime());
        break;
      case 'time_desc':
        filtered.sort((a, b) => new Date(b.submitTime).getTime() - new Date(a.submitTime).getTime());
        break;
    }
    
    return filtered;
  });
  
  onMounted(async () => {
    // 实际项目中这里应该调用API获取考试和成绩数据
    // if (courseId.value && examId.value) {
    //   try {
    //     const examRes = await getExamInfo(examId.value);
    //     exam.value = examRes.data;
    //     
    //     const resultsRes = await getExamResults(examId.value);
    //     results.value = resultsRes.data;
    //   } catch (error) {
    //     console.error('获取数据失败', error);
    //   }
    // }
  });
  
  const onBack = () => {
    router.back();
  };
  
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };
  
  const getStatusTagType = (status: string) => {
    switch (status) {
      case 'not_started': return 'primary';
      case 'in_progress': return 'warning';
      case 'finished': return 'success';
      default: return 'default';
    }
  };
  
  const getStatusText = (status: string) => {
    switch (status) {
      case 'not_started': return '未开始';
      case 'in_progress': return '进行中';
      case 'finished': return '已结束';
      default: return '未知';
    }
  };
  
  const getScoreClass = (score: number, totalScore: number) => {
    const percentage = score / totalScore;
    if (percentage < 0.6) return 'score-fail';
    if (percentage >= 0.9) return 'score-excellent';
    if (percentage >= 0.8) return 'score-good';
    return 'score-pass';
  };
  
  const exportResults = () => {
    // 实际项目中这里应该实现导出成绩功能
    showSuccessToast('成绩已导出');
  };
  </script>
  
  <style scoped>
  .exam-results {
    background-color: #f7f8fa;
    min-height: 100vh;
    padding-bottom: 80px;
  }
  
  .exam-info {
    background-color: #fff;
    padding: 16px;
    margin-bottom: 10px;
  }
  
  .exam-info h3 {
    margin: 0 0 12px 0;
    font-size: 18px;
  }
  
  .exam-details {
    color: #646566;
    font-size: 14px;
  }
  
  .exam-details .description {
    margin: 0 0 8px 0;
  }
  
  .exam-time {
    margin: 8px 0;
  }
  
  .exam-status {
    margin-top: 8px;
  }
  
  .results-summary {
    padding: 16px;
  }
  
  .summary-card {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin-bottom: 16px;
  }
  
  .summary-item {
    text-align: center;
    flex: 1;
    min-width: 80px;
    margin-bottom: 12px;
  }
  
  .label {
    font-size: 14px;
    color: #646566;
    margin-bottom: 6px;
  }
  
  .value {
    font-size: 20px;
    font-weight: bold;
    color: #1989fa;
  }
  
  .score-distribution {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
  }
  
  .score-distribution h4 {
    margin: 0 0 16px 0;
    font-size: 16px;
    color: #323233;
  }
  
  .chart-container {
    height: 200px;
  }
  
  .bar-chart {
    display: flex;
    height: 100%;
    justify-content: space-around;
    align-items: flex-end;
  }
  
  .bar-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 18%;
  }
  
  .bar {
    width: 100%;
    background-color: #1989fa;
    border-radius: 4px 4px 0 0;
    transition: height 0.3s;
  }
  
  .bar-label {
    margin-top: 8px;
    font-size: 12px;
    color: #646566;
  }
  
  .toolbar {
    display: flex;
    background: #fff;
    margin-bottom: 10px;
  }
  
  .toolbar .van-search {
    flex: 1;
  }
  
  .results-list {
    padding: 0 8px;
  }
  
  .student-info {
    display: flex;
    flex-direction: column;
  }
  
  .student-id {
    font-size: 13px;
  }
  
  .submission-time {
    font-size: 12px;
    color: #969799;
    margin-top: 4px;
  }
  
  .score {
    font-weight: bold;
  }
  
  .score-fail {
    color: #ee0a24;
  }
  
  .score-pass {
    color: #ff976a;
  }
  
  .score-good {
    color: #07c160;
  }
  
  .score-excellent {
    color: #1989fa;
  }
  
  .action-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  }
  </style>